//
// Created by 崔世强 on 2018/1/31.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import AliyunOSSiOS

class OSSTool {
    static let instance = OSSTool()
    
    var mClient: OSSClient!
    let OSS_BUCKET_PRIVATE = "waim-resource"
    
    private init() {
        let endpoint = "https://oss-cn-beijing.aliyuncs.com/"
        //        let authServerUrl = ""
        let appKey = "LTAI5tMoWEiJbitP8Fcfp5jz"
        let secret = "wfrmWnU4C3T5qHLxd6g0eScMtImWQM"
        //        let bucket = "waim-resource"
        //        var sign = OSSUtil.calBase64Sha1(withData: content, withSecret: "aaa")
        
        
        //        OSSStsTokenCredentialProvider(accessKeyId: <#T##String##Swift.String#>, secretKeyId: <#T##String##Swift.String#>, securityToken: <#T##String##Swift.String#>)
        let provider = OSSPlainTextAKSKPairCredentialProvider.init(plainTextAccessKey: appKey, secretKey: secret)
        //        var mProvider = OSSAuthCredentialProvider(authServerUrl: authServerUrl)
        //        var mProvider = OSSCustomSignerCredentialProvider.init(implementedSigner: (content, error) -> String? {
        //            var sign = OSSUtil.calBase64Sha1(withData: content, withSecret: "aaa")
        //            if sign != nil {
        //                error = nil
        //            } else {
        //                error = NSError(domain: "123", code: -1001,userInfo: "验证错误")
        //                return nil
        //            }
        //            return "OSS \(appKey):\(sign)"
        //        })
        mClient = OSSClient(endpoint: endpoint, credentialProvider: provider)
    }
    
    func putAudioFile(filePath: String, fileName: String) {
        let request = OSSPutObjectRequest()
        request.uploadingFileURL = URL(fileURLWithPath: filePath)
        request.bucketName = OSS_BUCKET_PRIVATE
        request.objectKey = "im/\(fileName).amr"
        request.uploadProgress = { (bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) -> Void in
            print("bytesSent:\(bytesSent),totalBytesSent:\(totalBytesSent),totalBytesExpectedToSend:\(totalBytesExpectedToSend)");
        };
        let task = mClient.putObject(request)
        task.continue({ (t) -> Any? in
            print(t)
            //            self.showResult(task: t)
        }).waitUntilFinished()
    }
    
    func getAudioFile(_ fileName: String){
        let request = OSSGetObjectRequest()
        request.bucketName = OSS_BUCKET_PRIVATE
        request.objectKey = "im/\(fileName).amr"
        request.downloadProgress = {(bytesWritten:Int64,totalBytesWritten:Int64,totalBytesExpectedToWrite:Int64) -> Void in
            //            print("bytesWritten:\(bytesWritten),totalBytesWritten:\(totalBytesWritten),totalBytesExpectedToWrite:\(totalBytesExpectedToWrite)");
        }
        request.downloadToFileURL = AppStatusManager.instance.urlForUser!.appendingPathComponent("audio",isDirectory: true)
            .appendingPathComponent("\(fileName).amr",isDirectory: false)
        let task = mClient.getObject(request)
        task.continue({ (t) -> Any? in
            print(t)
        }).waitUntilFinished()
    }
    
    func putImgFile(_ fileName:String,imgData:Data) {
        let request = OSSPutObjectRequest()
        request.uploadingData = imgData
        request.bucketName = OSS_BUCKET_PRIVATE
        request.objectKey = "im/img/\(fileName)"
        request.uploadProgress = { (bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) -> Void in
            //            print("bytesSent:\(bytesSent),totalBytesSent:\(totalBytesSent),totalBytesExpectedToSend:\(totalBytesExpectedToSend)")
        }
        let task = mClient.putObject(request)
        task.continue({ (t) -> Any? in
            print(t)
            //            self.showResult(task: t)
        }).waitUntilFinished()
    }
    
    func putImgFile(_ fileName:String,imgFile:URL) {
        let request = OSSPutObjectRequest()
        request.uploadingFileURL = imgFile
        request.bucketName = OSS_BUCKET_PRIVATE
        request.objectKey = "im/img/\(fileName)"
        request.uploadProgress = { (bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) -> Void in
            //            print("bytesSent:\(bytesSent),totalBytesSent:\(totalBytesSent),totalBytesExpectedToSend:\(totalBytesExpectedToSend)")
        }
        let task = mClient.putObject(request)
        task.continue({ (t) -> Any? in
            print(t)
            //            self.showResult(task: t)
        }).waitUntilFinished()
    }
    
    //上传db文件供分析
    func putDbFile(_ file:URL?,name:String) {
        //        if file == nil {
        //            return
        //        }
        //        let request = OSSPutObjectRequest()
        //        request.uploadingFileURL = file!
        //        request.bucketName = OSS_BUCKET_PRIVATE
        //        request.objectKey = "im/reportDb/\(name)"
        //        request.uploadProgress = { (bytesSent: Int, totalBytesSent: Int, totalBytesExpectedToSend: Int) -> Void in
        //            print("bytesSent:\(bytesSent),totalBytesSent:\(totalBytesSent),totalBytesExpectedToSend:\(totalBytesExpectedToSend)")
        //        }
        //        let task = mClient.putObject(request)
        //        task.continue({ (t) -> Any? in
        //            print(t)
        ////            self.showResult(task: t)
        //        }).waitUntilFinished()
    }
    
    func putFile(_ file:URL,name:String,progress: @escaping (_ progress:Double) -> (),onSuccess:@escaping (_ file:URL) -> (),onError: @escaping (_ error:Swift.Error?)-> Void){
        let request = OSSPutObjectRequest()
        request.uploadingFileURL = file
        request.bucketName = OSS_BUCKET_PRIVATE
        request.objectKey = "im/files/\(name)"
        request.uploadProgress = { (bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) -> Void in
            print("bytesSent:\(bytesSent),totalBytesSent:\(totalBytesSent),totalBytesExpectedToSend:\(totalBytesExpectedToSend)")
            let p = Double(totalBytesExpectedToSend) / Double(totalBytesSent)
            progress(p)
        }
        let task = mClient.putObject(request)
        task.continue({ (t) -> Any? in
            if (task.isCompleted) {
                onSuccess(file)
            } else {
                onError(task.error)
            }
            return nil;
        })
    }
    
    func getSensitiveFile(_ complete:@escaping (_ fileName:String,_ success:Bool,_ error:Swift.Error?) -> ()) {
        let request = OSSGetObjectRequest()
        request.bucketName = OSS_BUCKET_PRIVATE
        request.objectKey = "im/sensitive/\(sensitiveFileName)"
        request.downloadProgress = {(bytesWritten:Int64,totalBytesWritten:Int64,totalBytesExpectedToWrite:Int64) -> Void in
            //            print("bytesWritten:\(bytesWritten),totalBytesWritten:\(totalBytesWritten),totalBytesExpectedToWrite:\(totalBytesExpectedToWrite)");
        }
        if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            request.downloadToFileURL = dir.appendingPathComponent(sensitiveFileName,isDirectory: false)
            let task = mClient.getObject(request)
            task.continue({ (t) -> Any? in
                complete(sensitiveFileName,task.isCompleted,task.error)
                return nil;
            })
        }
    }
}
